package com.oriental.manage.controller.speciallyUpdate;

import com.oriental.check.commons.util.BeanMapperUtil;
import com.oriental.manage.core.paging.Pagination;
import com.oriental.manage.core.response.ResponseDTO;
import com.oriental.manage.core.utils.SessionUtils;
import com.oriental.manage.model.specially.AreaNumber;
import com.oriental.manage.pojo.specially.BatchMessage;
import com.oriental.manage.pojo.specially.MerchantRiskInfo;
import com.oriental.manage.service.specially.BatchMessageService;
import com.oriental.manage.service.specially.MerchantRiskInfoService;
import com.oriental.paycenter.commons.utils.DateUtil;
import com.oriental.paycenter.commons.utils.RandomMath;
import com.oriental.riskfront.api.enums.TransCode;
import com.oriental.riskfront.api.model.specially.MerchantRiskInfoDto;
import com.oriental.riskfront.api.model.specially.MerchantRiskInfoUpdateDto;
import com.oriental.riskfront.api.model.specially.PersonRiskInfoDto;
import com.oriental.riskfront.api.model.specially.ResponseModel;
import com.oriental.riskfront.api.service.DataDictInterface;
import com.oriental.riskfront.api.service.RiskMsgSearchForUpdateInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by luoxin on 2017/4/20.
 */
@Slf4j
@Controller
@RequestMapping("riskInfo")
public class MerchantRiskInfoUpdateController {


    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private MerchantRiskInfoService merchantRiskInfoService;
    @Autowired
    private DataDictInterface dataDictInterface;
    @Autowired
    private RiskMsgSearchForUpdateInterface riskMsgSearchForUpdateInterface;
    @Autowired
    private BatchMessageService batchMessageService;

    @RequestMapping("merchantRiskUpdate/init")
    public String init() {
        return "speciallyUpdate/searchMerchantRiskMsg";
    }

    @RequestMapping("merchantRiskUpdate/search")
    @ResponseBody
    public ResponseDTO<Pagination<MerchantRiskInfo>> queryPage(Pagination<MerchantRiskInfo> pagination, MerchantRiskInfo userInfo) {
        ResponseDTO<Pagination<MerchantRiskInfo>> responseDTO = new ResponseDTO<Pagination<MerchantRiskInfo>>();
        try {
            log.info("查询商户风险变更请求参数,userInfo:{}",userInfo);
             MerchantRiskInfoDto merrchantRiskInfoDto= BeanMapperUtil.objConvert(userInfo,MerchantRiskInfoDto.class);
           ResponseModel<List<MerchantRiskInfoUpdateDto>> responseModel= riskMsgSearchForUpdateInterface.queryMerchantRiskInfoList(merrchantRiskInfoDto);
            if(!responseModel.isSuccess()){
                responseDTO.setSuccess(false);
                responseDTO.setMsg(responseModel.getErrorMsg());
                return responseDTO;
            }
            List<MerchantRiskInfoUpdateDto> merchantRiskInfoDtoList = responseModel.getResult();
            List<MerchantRiskInfo> listBody=new ArrayList<>();
            List<Map<String, Object>> dataAddress = dataDictInterface.getDataAddress("ADDRESS_Select");
            for(MerchantRiskInfoUpdateDto merchantRiskInfoDto:merchantRiskInfoDtoList){

                 String areaCode=merchantRiskInfoDto.getOccurarea();
                //String areaCode="210000,220000,210100";
                MerchantRiskInfo info = BeanMapperUtil.objConvert(merchantRiskInfoDto, MerchantRiskInfo.class);
                if(areaCode!=null && !"".equals(areaCode)) {
                    String[] stringArr = areaCode.split(",");
                    List<AreaNumber> basicData = new ArrayList<>();
                    for (int i = 0; i < stringArr.length; i++) {
                        AreaNumber areaNumber = new AreaNumber();
                        for (Map<String, Object> map : dataAddress) {
                            String areaCo = (String) map.get("areaCode");
                            String areaCoSub = areaCo.substring(0, 2);
                            String areaNa = (String) map.get("areaName");
                            if (areaCo.equals(stringArr[i])) {
                                areaNumber.setAreaCode(areaCo);
                                areaNumber.setAreaName(areaNa);
                                areaNumber.setCityName(areaNa);
                                basicData.add(areaNumber);
                            } else {
                                if (stringArr[i].length() > 1) {
                                    if (areaCoSub.equals(stringArr[i].substring(0, 2))) {
                                        areaNumber.setAreaCode(areaCo);
                                        areaNumber.setAreaName(areaNa);
                                        List<Map<String, Object>> citys = (List<Map<String, Object>>) map.get("citys");
                                        for (Map<String, Object> mapCity : citys) {
                                            String cityCo = (String) mapCity.get("cityCode");
                                            String cityNa = (String) mapCity.get("cityName");
                                            if (cityCo.equals(stringArr[i])) {
                                                areaNumber.setCityCode(cityCo);
                                                areaNumber.setCityName(areaNa+cityNa);
                                            }
                                        }
                                        basicData.add(areaNumber);
                                    }
                                }
                            }
                        }
                    }
                    info.setBasicData(basicData);
                }
                info.setRiskId(info.getId());
                listBody.add(info);
            }
            responseDTO.setSuccess(true);
            pagination.setRowCount(listBody.size());
            pagination.setList(listBody);
            log.info("商户风险信息变更查询,pagination:{}",pagination);
            responseDTO.setObject(pagination);
        } catch (Exception e) {
            log.error("查询失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }
        return responseDTO;
    }

    @RequestMapping("merchantRiskUpdate/toUpdate")
    public String update() {
        return "speciallyUpdate/updateMerchantRiskInfo";
    }
    //失效
    @RequestMapping("merchantRiskUpdate/toInvali")
    public String toInvali() {
        return "speciallyUpdate/invalidMerchantRiskInfo";
    }
    //降级
    @RequestMapping("merchantRiskUpdate/toDecline")
    public String toDecline() {
        return "speciallyUpdate/declineMerchantRiskInfo";
    }
    @RequestMapping("merchantRiskUpdate/toDetail")
    public String queryDetail() {
        return "speciallyUpdate/merchantRiskInfoUpdateDetail";
    }

    @RequestMapping("merchantRiskUpdate/update")
    @ResponseBody
    @Transactional
    public ResponseDTO<String> updatePersonRiskInfo(@RequestBody MerchantRiskInfo merchantRiskInfo) {
        ResponseDTO<String> responseDTO = new ResponseDTO<String>();
        BatchMessage batchMessage = new BatchMessage();
        try {//Z2012931000018
            String areaCode=merchantRiskInfo.getOccurarea();
            if(areaCode.length()>1){
                String code=areaCode.substring(0,1);
                if(",".equals(code)){
                    merchantRiskInfo.setOccurarea(areaCode.substring(1));
                }
            }else{
                merchantRiskInfo.setOccurarea("");
            }
            String Id=DateUtil.getCurrent().concat(RandomMath.getNum(5));
            String user = SessionUtils.getUserName();
            merchantRiskInfo.setRiskId(merchantRiskInfo.getId());
            merchantRiskInfo.setId(Id);
            //merchantRiskInfo.setOrgId("Z2012931000018");
            //merchantRiskInfo.setCusProperty("02");
            //merchantRiskInfo.setRepType("03");
            merchantRiskInfo.setUpdateType("01");//01修改
            merchantRiskInfo.setStatus("00");//初始状态
            merchantRiskInfo.setRepPerson(user);
            batchMessage.setId(DateUtil.getCurrent().concat(RandomMath.getNum(5)));
            batchMessage.setSubmitMsgId(Id);
            batchMessage.setStatus("00");
            batchMessage.setDeleteFlag("0");
            batchMessage.setCount(1);
            batchMessage.setTrnxCode(TransCode.UP0004.getCode());
            batchMessage.setReportDate(new Date());
            batchMessage.setCreateBy(user);
            batchMessage.setMerchant(merchantRiskInfo.getCusCode());
            batchMessage.setRiskType(merchantRiskInfo.getRiskType());
            batchMessage.setLevel(merchantRiskInfo.getLevel());
            log.info("商户风险信息变更,merchantRiskInfo:{}",merchantRiskInfo);
           // merchantRiskInfoService.insert(merchantRiskInfo, responseDTO);
           // batchMessageService.insertBatchMessage(batchMessage);
            if(merchantRiskInfo.getRiskId()!=null||!"".equals(merchantRiskInfo.getRiskId())){
                int number =  merchantRiskInfoService.queryByRiskId(merchantRiskInfo.getRiskId());
                if(number<1){
                    merchantRiskInfoService.insert(merchantRiskInfo, responseDTO);
                    batchMessageService.insertBatchMessage(batchMessage);
                }else{
                    responseDTO.setSuccess(false);
                    responseDTO.setMsg("该条记录已做处理，请到上报审核页面审批！");
                }
            }
        } catch (Exception e) {
            log.error("商户风险信息变更失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }
        return responseDTO;
    }

    @RequestMapping("merchantRiskUpdate/invalid")
    @ResponseBody
    @Transactional
    //失效
    public ResponseDTO<String> invalid(@RequestBody MerchantRiskInfo merchantRiskInfo) {
        ResponseDTO<String> responseDTO = new ResponseDTO<String>();
        BatchMessage batchMessage = new BatchMessage();
        try {//Z2012931000018
            String areaCode=merchantRiskInfo.getOccurarea();
            if(areaCode.length()>1){
                String code=areaCode.substring(0,1);
                if(",".equals(code)){
                    merchantRiskInfo.setOccurarea(areaCode.substring(1));
                }
            }else{
                merchantRiskInfo.setOccurarea("");
            }
            String user = SessionUtils.getUserName();
            String Id=DateUtil.getCurrent().concat(RandomMath.getNum(5));
            merchantRiskInfo.setRiskId(merchantRiskInfo.getId());
            merchantRiskInfo.setId(Id);
            //merchantRiskInfo.setOrgId("Z2012931000018");
            //merchantRiskInfo.setCusProperty("02");
            //merchantRiskInfo.setRepType("03");
            merchantRiskInfo.setUpdateType("02");//02失效
            merchantRiskInfo.setStatus("00");//初始状态
            merchantRiskInfo.setRepPerson(user);
            batchMessage.setId(DateUtil.getCurrent().concat(RandomMath.getNum(5)));
            batchMessage.setSubmitMsgId(Id);
            batchMessage.setStatus("00");
            batchMessage.setDeleteFlag("0");
            batchMessage.setCount(1);
            batchMessage.setTrnxCode(TransCode.UP0004_1.getCode());
            batchMessage.setReportDate(new Date());
            batchMessage.setCreateBy(user);
            batchMessage.setMerchant(merchantRiskInfo.getCusCode());
            batchMessage.setRiskType(merchantRiskInfo.getRiskType());
            batchMessage.setLevel(merchantRiskInfo.getLevel());
            log.info("商户风险信息失效,merchantRiskInfo:{}",merchantRiskInfo);
            if(merchantRiskInfo.getRiskId()!=null||!"".equals(merchantRiskInfo.getRiskId())){
                int number =  merchantRiskInfoService.queryByRiskId(merchantRiskInfo.getRiskId());
                if(number<1){
                    merchantRiskInfoService.insert(merchantRiskInfo, responseDTO);
                    batchMessageService.insertBatchMessage(batchMessage);
                }else{
                    responseDTO.setSuccess(false);
                    responseDTO.setMsg("该条记录已做处理，请到上报审核页面审批！");
                }
            }
        } catch (Exception e) {
            log.error("新增失效数据失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }
        return responseDTO;
    }
    @RequestMapping("merchantRiskUpdate/decline")
    @ResponseBody
    @Transactional
    //降级
    public ResponseDTO<String> decline(@RequestBody MerchantRiskInfo merchantRiskInfo) {
        ResponseDTO<String> responseDTO = new ResponseDTO<String>();
        BatchMessage batchMessage = new BatchMessage();
        try {//Z2012931000018
            //String Id = merchantRiskInfo.getRiskId();
            String areaCode=merchantRiskInfo.getOccurarea();
            if(areaCode.length()>1){
                String code=areaCode.substring(0,1);
                if(",".equals(code)){
                    merchantRiskInfo.setOccurarea(areaCode.substring(1));
                }
            }else{
                merchantRiskInfo.setOccurarea("");
            }
            String user = SessionUtils.getUserName();
            String Id=DateUtil.getCurrent().concat(RandomMath.getNum(5));
            merchantRiskInfo.setRiskId(merchantRiskInfo.getId());
            merchantRiskInfo.setId(Id);
            //merchantRiskInfo.setOrgId("Z2012931000018");
            //merchantRiskInfo.setCusProperty("02");
            //merchantRiskInfo.setRepType("03");
            merchantRiskInfo.setUpdateType("03");//02降级
            merchantRiskInfo.setStatus("00");//初始状态
            merchantRiskInfo.setRepPerson(user);
            batchMessage.setId(DateUtil.getCurrent().concat(RandomMath.getNum(5)));
            batchMessage.setSubmitMsgId(Id);
            batchMessage.setStatus("00");
            batchMessage.setDeleteFlag("0");
            batchMessage.setCount(1);
            batchMessage.setTrnxCode(TransCode.UP0004_2.getCode());
            batchMessage.setReportDate(new Date());
            batchMessage.setCreateBy(user);
            batchMessage.setMerchant(merchantRiskInfo.getCusCode());
            batchMessage.setRiskType(merchantRiskInfo.getRiskType());
            batchMessage.setLevel(merchantRiskInfo.getLevel());
            log.info("商户风险信息降级,merchantRiskInfo:{}",merchantRiskInfo);
            //merchantRiskInfoService.insert(merchantRiskInfo, responseDTO);
            //batchMessageService.insertBatchMessage(batchMessage);
            if(merchantRiskInfo.getRiskId()!=null||!"".equals(merchantRiskInfo.getRiskId())){
                int number =  merchantRiskInfoService.queryByRiskId(merchantRiskInfo.getRiskId());
                if(number<1){
                    merchantRiskInfoService.insert(merchantRiskInfo, responseDTO);
                    batchMessageService.insertBatchMessage(batchMessage);
                }else{
                    responseDTO.setSuccess(false);
                    responseDTO.setMsg("该条记录已做处理，请到上报审核页面审批！");
                }
            }
        } catch (Exception e) {
            log.error("新增降级数据失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }
        return responseDTO;
    }
}
